<?php

namespace app\member\controller;

use think\Controller;
use think\Exception;
use think\Request;
use think\Session;

class Login extends Controller
{
    /**
     * 后台登录
     * @return mixed
     */
    public function index()
    {
        if (Session::has('uid') && Session::has('token')) {
            $this->redirect('member/index/index');
        } else {
            return $this->fetch();
        }
    }

    public function login()
    {
        $request = Request::instance();
        $param = $request->param();

        if ($this->request->isPost()) {
            $data = $this->request->only(['username', 'password', 'verify']);
            $validate_result = $this->validate($data, 'Login');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data = [];
                $data['username'] = $param['username'];
                $data['password'] = md5($param['password'] . config('salt'));
                $data['app_id'] = config('member_app.app_id');
                $time = time();
                $data['time'] = $time;
                $data['app_secret_des'] = md5(config('member_app.app_id') . config('member_app.app_secret') . $time);

                try {
                    $result = doCurl(config('member_app.url')['member_login'], 1, $data);
                    $res = json_decode($result, true);
                    if($res['code'] != 200) {
                        return json($res);
                    }
                    Session::set('uid', $res['uid']);
                    Session::set('name', $res['name']);
                    Session::set('token', $res['token']);
                    Session::set('time_out', $res['time_out']);
                    return json($res);
                } catch (Exception $e) {
                    $data['code'] = 401;
                    $data['msg'] = '未知错误';
                    $data['error_code'] = 10001;
                    return json($data);
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::delete('uid');
        Session::delete('name');
        Session::delete('token');
        Session::delete('time_out');
        $this->success('退出成功', 'member/login/index');
    }

}
